import os
import sys
import platform
import subprocess
import urllib.request

# 确定Python版本和系统架构
def get_python_version():
    return f"{sys.version_info.major}{sys.version_info.minor}"

def get_architecture():
    return "amd64" if platform.machine().endswith('64') else "x86"

# 下载文件
def download_file(url, filename):
    print(f"正在下载: {filename}")
    try:
        urllib.request.urlretrieve(url, filename)
        print("下载成功!")
        return True
    except Exception as e:
        print(f"下载失败: {e}")
        return False

# 运行命令
def run_command(command):
    print(f"运行命令: {' '.join(command)}")
    try:
        result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"命令失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False

# 主函数
def main():
    print("===== dlib和face_recognition安装脚本 ======")

    # 获取系统信息
    python_version = get_python_version()
    architecture = get_architecture()
    print(f"Python版本: {python_version}")
    print(f"系统架构: {architecture}")

    # 设置dlib版本和下载URL
    dlib_version = "19.24.2"
    wheel_filename = f"dlib-{dlib_version}-cp{python_version}-cp{python_version}-win_{architecture}.whl"
    download_url = f"https://pypi.tuna.tsinghua.edu.cn/packages/0e/ce/f8a3cff33ac03a8219768f0694c5d703c8e037e6aba2e865f9bae22ed6f/{wheel_filename}"

    # 下载wheel文件
    if not download_file(download_url, wheel_filename):
        print("\n手动下载指南:")
        print("1. 访问: https://pypi.org/project/dlib/#files")
        print(f"2. 下载适合您Python版本({python_version})和系统架构({architecture})的wheel文件")
        print("3. 将文件放在当前目录")
        print("4. 重新运行此脚本")
        return

    # 安装dlib
    if not run_command([sys.executable, "-m", "pip", "install", wheel_filename]):
        print("dlib安装失败")
        return

    # 验证dlib安装
    try:
        import dlib
        print(f"dlib版本: {dlib.__version__}")
    except ImportError:
        print("dlib验证失败")
        return

    # 安装face_recognition
    if not run_command([sys.executable, "-m", "pip", "install", "face_recognition", "-i", "https://pypi.tuna.tsinghua.edu.cn/simple", "--default-timeout=120"]):
        print("face_recognition安装失败")
        return

    # 验证face_recognition安装
    try:
        import face_recognition
        print(f"face_recognition版本: {face_recognition.__version__}")
    except ImportError:
        print("face_recognition验证失败")
        return

    print("\n===== 所有安装完成! ======")

if __name__ == "__main__":
    main()